const conn = require('../config/datasql');
/** 动物列表 */
const getAnimalList = (req, res) => {
  if (!req.query.page && !req.query.pageSize) {
    req.query = {
      page: 0,
      pageSize: 5,
    };
  }
  if (req.query.page) {
    req.query.page -= 1;
  }

  let sql = `SELECT * FROM animal limit ${req.query.page},${req.query.pageSize};`;
  conn(sql, (err, result) => {
    if (err) {
      res.send({ code: 503, msg: '服务器目前异常!请稍后重试!' });
    } else {
      res.send({
        code: 1,
        list: result.map((i) => ({ ...i, img: i.img.split(',') })),
        count: result.length,
      });
    }
  });
};

/** 新增动物 */
const adddAnimal = async (req, res) => {
  req.body.img = req.body.img.join(',');
  let sql = `select*from animal where title="${req.body.title}" `;
  conn(sql, (err, result) => {
    if (err) {
      res.send({ code: 50111, msg: '服务器目前异常!请稍后重试!' });
    } else {
      if (result.length !== 0) {
        res.send({ code: 0, msg: '此动物已存在,请重新进行添加!' });
      } else {
        let addsql = 'insert into animal set ?';
        conn(
          addsql,
          (e, r) => {
            if (e) {
              res.send({ code: 503, msg: '服务器目前异常!请稍后重试!' });
            } else {
              if (r.affectedRows == 1) {
                res.send({ code: 1, msg: '新增成功！' });
              } else {
                res.send({ code: 0, msg: '新增失败,请稍后重试!' });
              }
            }
          },
          req.body
        );
      }
    }
  });
};

/** 删除动物  */
const delAnimal = (req, res) => {
  let sql = `delete from animal where id = ${req.body.id}`;
  conn(sql, (err, result) => {
    if (err) {
      res.send({ code: 503, msg: '服务器目前异常!请稍后重试!' });
    } else {
      if (result.affectedRows == 1) {
        res.send({ code: 1, msg: '删除成功' });
      } else {
        res.send({ code: 0, msg: '修改失败,可能是服务器原因,期待您的重试' });
      }
    }
  });
};

/** 根据类型 返回所有的动物 */
const getListByType = (req, res) => {
  let sql = `select*from animal where typeId = ${req.body.typeId}`;
  conn(sql, (err, result) => {
    if (err) {
      res.send({ code: 503, msg: '服务器目前异常!请稍后重试!' });
    } else {
      res.send({
        code: 1,
        list: result.map((i) => ({ ...i, img: i.img.split(',') })),
        count: result.length,
      });
    }
  });
};

/** 根据id 查询 动物详情 */
const getAnimalById = (req, res) => {
  let sql = `select*from animal where id = ${req.body.id}`;
  conn(sql, (err, result) => {
    if (err) {
      res.send({ code: 503, msg: '服务器目前异常!请稍后重试!' });
    } else {
      res.send({
        code: 1,
        animal: { ...result[0], img: result[0].img.split(',') },
        count: result.length,
      });
    }
  });
};

module.exports = {
  getAnimalList,
  adddAnimal,
  getListByType,
  delAnimal,
  getAnimalById,
};
